import * as THREE from "three";
import * as d3 from 'd3'

const UtilThreeMap = {
    initMap(chinaJson) {
        // 建一个空对象存放对象
        let map = new THREE.Object3D();

        let _this = this;

        // 墨卡托投影转换
        const projection = d3.geoMercator().center([104.0, 37.5]).scale(80).translate([0, 0]);

        chinaJson.features.forEach(elem => {
            // 定一个省份3D对象
            const province = new THREE.Object3D();
            // 每个的 坐标 数组
            const coordinates = elem.geometry.coordinates;
            // 循环坐标数组
            coordinates.forEach(multiPolygon => {

                multiPolygon.forEach(polygon => {
                    const shape = new THREE.Shape();
                    const lineMaterial = new THREE.LineBasicMaterial({color: 'white'});
                    const lineGeometry = new THREE.BufferGeometry();

                    const pointsArray = new Array()
                    for (let i = 0; i < polygon.length; i++) {
                        let [x, y] = polygon[i];
                        x -= 110
                        y -= 40
                        if (i === 0) {
                            shape.moveTo(x, -y, 1);
                        }
                        shape.lineTo(x, -y, 1);
                        pointsArray.push(new THREE.Vector3(x, -y, 0))
                    }

                    //用这个api传入顶点数组
                    lineGeometry.setFromPoints(pointsArray)

                    const extrudeSettings = {
                        depth: 0.1,
                        bevelEnabled: false
                    };

                    const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings)
                    const material = new THREE.MeshBasicMaterial({color: '#02A1E2', transparent: true, opacity: 0.6})
                    const material1 = new THREE.MeshBasicMaterial({color: '#3480C4', transparent: true, opacity: 0.5})
                    const mesh = new THREE.Mesh(geometry, [material, material1])
                    const line = new THREE.Line(lineGeometry, lineMaterial)
                    province.add(mesh)
                    province.add(line)

                })

            })

            // 将geo的属性放到省份模型中
            province.properties = elem.properties;
            if (elem.properties.contorid) {
                const [x, y] = projection(elem.properties.contorid);
                province.properties._centroid = [x, y];
            }

            map.add(province);

        })

        return map
    }
}

export default UtilThreeMap